package controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.concurrent.locks.Lock;

import data.IData;
import functionality.ITransmitter;

public class OperatorLoginController implements Runnable, IOperatorLoginController {
	
	private String host;
	private int port;
	private ITransmitter transmit;
	
	public OperatorLoginController(String[] args, ITransmitter transmit){
		this.host = args[0];
		this.port = Integer.parseInt(args[1]);	
		this.transmit = transmit;
	}

	@Override
	public void run() {
		try (Socket	socket2 = new Socket(host, port);
				PrintWriter out = new PrintWriter(socket2.getOutputStream(), true);
				BufferedReader in = new BufferedReader(new InputStreamReader(socket2.getInputStream()));){	
			Lock lock = transmit.getLock();
			if (lock.tryLock()){
				System.out.println("Operatør-login startet!");
				try {
					int userID = transmit.getInputUserId(out, in);
					System.out.println("Indtastet userID: " + userID);
					String password = transmit.getInputPassword(out, in);
					System.out.println("Indtastet password: " + password);
					
					if (transmit.getOprPassword(userID).equals(password)){
						transmit.dispTxtScl(out, in, "Operatoer godkendt");
						System.out.println("Operatør " + userID + " er logget ind.");
					} else {
						transmit.dispTxtScl(out, in, "Forkert login");
						System.out.println("Operatør " + userID + " har indtastet forkert password.");
					}
					
					System.out.println("Operatør-login tråd termineret (Operatør har indtastet UserID + Password, eller afbrudt loginsekvens).");
				} finally {
					lock.unlock();
				}
			}
			else {
				System.out.println("Operatør-login kunne ikke startes. Forsøg igen senere.");
			}
		}catch (UnknownHostException e) {
			System.out.println("Ukendt host: " + host);
			System.exit(1);
		} catch (IOException e) {
			System.out.println("Ingen forbindelse... Genstart program.");
			System.exit(1);
		}
	}
}
